package com.snowy.framework.aspect;

import java.util.Map;

import com.snowy.framework.common.base.model.QueryModel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 分页查询却面
 *
 * @author Melody
 *
 */
@Aspect
@Component
public class SlicedQueryAspect {

	@SuppressWarnings("unchecked")
	@Around("@annotation(com.snowy.framework.annotation.SlicedQuery)")
	public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		Object object = null;
//		try {
			Integer pageIndex = null;
			Integer pageSize = null;
			// 获取参数集合
			Object[] args = proceedingJoinPoint.getArgs();
			// 分页查询参数为空
			if (args.length < 1) {
				pageIndex = QueryModel.PAGE_INDEX;
				pageSize = QueryModel.PAGE_SIZE;
			}
			// 遍历参数
			for (Object arg : args) {
				// 如果是模型的方式查询
				if (arg instanceof QueryModel) {
					pageIndex = ((QueryModel) arg).getPageIndex();
					pageSize = ((QueryModel) arg).getPageSize();
					// 结束循环
					break;
				}
				// 如果是map的方式查询
				if (arg instanceof Map) {
					Map<String, Object> map = (Map<String, Object>) arg;
					pageIndex = map.get(QueryModel.PAGE_INDEX_STR) == null ? QueryModel.PAGE_INDEX : Integer.valueOf(map.get(QueryModel.PAGE_INDEX_STR).toString());
					pageSize = map.get(QueryModel.PAGE_SIZE_STR) == null ? QueryModel.PAGE_SIZE : Integer.valueOf(map.get(QueryModel.PAGE_SIZE_STR).toString());
					break;
				}
			}
			// 初始化分页对象
			object = proceedingJoinPoint.proceed();
//		} catch (Throwable e) {
//			throw new UABPException(e.getMessage());
//		}
		return object;
	}
}
